import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider, message, DatePicker,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import CheckCompany from './check';
import styles from '../UserManage.less';
import DescView from './descView';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ debtModels, loading }) => ({
  debtModels,
  loading: loading.models.debtModels,
}))

@Form.create()
class CompanyManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: {},
    formValues: {},
    pagination: {},
    lookDescView: false,
    visibleCheck: false,
  };

  status = [
    '募集中', '待审核', '驳回', '募满',
  ];


  constructor(props) {
    super(props);

  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { status } = this.state;
    // 请求用户列表
    dispatch({
      type: 'debtModels/fetch',
      payload: {
        status: status,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'debtModels/fetch',
      payload: params,
    });
  };
  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'debtModels/fetch',
      payload: {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  // 搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { status } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        status: status,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'debtModels/fetch',
        payload: values,
      });
    });
  };
  // 审核
  handleCheck = (flag, record) => {
    this.setState({
      visibleCheck: !!flag,
      selectedRows: record,
    });
  };

  passCheck = (flag, record) => {
    const { dispatch } = this.props;
    const { selectedRows, pagination } = this.state;
    let _this = this;
    dispatch({
      type: 'debtModels/audit',
      payload: { code: selectedRows.debtNo, ...record },
      callback(res) {
        if (res.code === 200) {
          _this.handleCheck(false, []);
          dispatch({
            type: 'debtModels/fetch',
            payload: pagination,
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }

      },
    });
  };

  //查看
  handleLookDesc = (flag, record) => {
    console.log(record);
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'debtModels/debtDesc',
          payload: { debtNo: record.debtNo },
        });
      }
    });

  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="用户编号">
              {getFieldDecorator('userNo')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('startTime')(<DatePicker placeholder="选择开始时间"
                                                          style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="结束时间">
              {getFieldDecorator('endTime')(
                <DatePicker placeholder="选择结束时间"
                            style={{ width: '100%' }}/>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>


      </Form>
    );
  }


  render() {
    const { debtModels: { data, debtDescData }, loading } = this.props;
    const { selectedRows, visibleCheck, lookDescView } = this.state;
    const columns = [
      {
        title: '项目名称',
        dataIndex: 'projectName',

      },
      {
        title: '订单编号',
        dataIndex: 'orderNo',
      },
      {
        title: '转让金额',
        dataIndex: 'amount',
      },

      {
        title: '折让率',
        dataIndex: 'sale',
      },

      {
        title: '用户编号',
        dataIndex: 'userNo',
      },
      {
        title: '项目类型',
        dataIndex: 'type',
        render: ((text) => {
          return <span>{text === 1 ? '正常' : '逾期'}</span>;
        }),
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: ((text) => {
          return <span>{this.status[text - 1]}</span>;
        }),
      },
      {
        title: '操作',
        render: (text, record) => {
          return (<Fragment>
            {
              powerBtnFunc('100106', [
                <a key={'check'} disabled={record.status !== 2} onClick={() => this.handleCheck(true, record)}>审核</a>,
                <Divider key={'divider'} type="vertical"/>,
              ])
            }
            {
              powerBtnFunc('100105', <a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>)
            }

          </Fragment>);
        },

      },
    ];

    return (
      <PageHeaderWrapper title="债转列表">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey={'debtNo'}
              columns={columns}
              rowSelectHide={true}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={debtDescData ? debtDescData : {}}
          lookDescView={lookDescView}/>

        <CheckCompany visibleCheck={visibleCheck} passCheck={this.passCheck} handleCheck={this.handleCheck}/>
      </PageHeaderWrapper>
    );
  }
}

export default CompanyManage;
